import { useRequest } from 'ahooks'
import { Carousel } from 'antd'
import * as echarts from 'echarts'
import {
  forwardRef,
  useContext,
  useEffect,
  useImperativeHandle,
  useRef,
  useState
} from 'react'
import CountUp from 'react-countup'

import { priceSwitch } from '@/utils/compUtils'

import { ModuleTitle } from '../../ModuleTitle'
import { ContentTsx } from '../../contentTsx'
import { colorLinearData, cyry } from '../../data'

const PersonJobPie = forwardRef<
  { resize: () => void },
  { pieEndTotalDirvers: number }
>((props, ref) => {
  const { pieEndTotalDirvers } = props
  const { selectedAssociationItem, refreshFlag } = useContext(ContentTsx)

  const chartDom = useRef<HTMLDivElement>(null)
  const personChartRef = useRef<echarts.EChartsType>()

  /*获取图表数据 设置图表数据*/
  const [allSum, setallSum] = useState<any>()
  const { data: optionData } = useRequest(
    async () => {
      const data = await cyry({ entId: selectedAssociationItem.key })
      setallSum(data.data.allSum || 0)
      return data.data.grops
    },
    {
      refreshDeps: [selectedAssociationItem.key, refreshFlag]
    }
  )

  /*设置图表数据*/
  useEffect(() => {
    if (!chartDom.current) {
      return
    }
    const optData = (optionData ?? []).filter((v: any) => v.value)
    let fData: any[] = []
    if (optData.length) {
      fData = optionData
    }
    const data2 = fData.map((v: any, i: any) => {
      return {
        ...v,
        labelColor: colorLinearData[i][2],
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: colorLinearData[i][0] }, // 0% 处的颜色
              { offset: 1, color: colorLinearData[i][1] } // 100% 处的颜色
            ],
            global: false // 缺省为 false
          }
        }
      }
    })
    if (!personChartRef.current) {
      // 初始化值
      personChartRef.current = echarts.init(chartDom.current, null, {
        renderer: 'canvas'
      })
      personChartRef.current.setOption({
        showEmptyCircle: true,
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['68%', '85%'],
            // padAngle: 4,
            labelLine: {
              show: false
            },
            label: {
              show: false
            },
            itemStyle: {
              // borderRadius: 10,
              borderColor: '#181818',
              borderWidth: 2
            },
            avoidLabelOverlap: false,
            animation: true,
            hoverAnimation: true,
            emphasis: {
              scale: true
            },
            emptyCircleStyle: {
              color: 'rgba(0, 0, 0, 0.60)' // 设置没数据的样式
            }
          }
        ]
      })
    } else if (personChartRef.current) {
      personChartRef.current.setOption({
        series: [
          {
            data: data2,
            emptyCircleStyle: {
              color: 'rgba(0, 0, 0, 0.60)' // 设置没数据的样式
            }
          }
        ]
      })
    }
  }, [optionData])

  useEffect(() => {
    return () => {
      if (personChartRef.current && !personChartRef.current.isDisposed()) {
        // echarts.dispose(personChartRef.current) //销毁
        personChartRef.current.dispose()
      }
    }
  }, [])

  /*视口改变 echarts  -resize*/
  useImperativeHandle(ref, () => ({
    resize: () => {
      if (personChartRef.current) {
        // console.log("--Left--PersonJobPie--resize--")
        personChartRef.current.resize()
      }
    }
  }))

  return (
    <div
      className="bigscreen-module ms-module"
      style={{ height: 193, overflow: 'hidden' }}
    >
      <ModuleTitle title={'从业人员数据分析'}></ModuleTitle>
      <div
        className="bigscreen-content flexr alc juc"
        style={{ paddingTop: 5, paddingBottom: 14, position: 'relative' }}
      >
        <div
          style={{
            position: 'absolute',
            zIndex: 1,
            left: 0,
            bottom: 0,
            height: 151,
            width: '100%'
            // padding: "0px 23px"
          }}
        >
          <DataCarousel
            data={optionData || []}
            pieEndTotalDirvers={pieEndTotalDirvers}
          ></DataCarousel>
        </div>
        <div
          className="flexr alc juc"
          style={{ zIndex: 9, width: 180, position: 'relative' }}
        >
          <div className="pie-box">
            <div className="pie-raiusLine"> </div>
            <div className="labelContent flexr alc juc" style={{ zIndex: 4 }}>
              <div>
                <div className="item-p">
                  <CountUp start={0} end={allSum} duration={1}></CountUp>
                </div>
                <div className="item-n">从业人员总数</div>
              </div>
            </div>
            <div
              ref={chartDom}
              style={{ width: '132px', height: '132px' }}
              className="echarts-pie"
            ></div>
          </div>
        </div>
      </div>
    </div>
  )
})

export default PersonJobPie
/**
 * desc 走马灯数据展示
 */
interface UlDivProps {
  data?: any[]
  pieEndTotalDirvers: number
}
export function DataCarousel({
  data = [],
  pieEndTotalDirvers
}: {
  data: any[]
  pieEndTotalDirvers: number
}) {
  //数据拆分
  const [groupList, setGroupList] = useState<any[][]>([])
  const splitArray = (arr: any[], chunkSize: number) => {
    const result = []
    for (let i = 0; i < arr.length; i += chunkSize) {
      result.push(arr.slice(i, i + chunkSize))
    }
    return result
  }
  //监听数据改变
  useEffect(() => {
    if (data) {
      const chunked = splitArray(data, 6)
      setGroupList(chunked)
    }
  }, [data])

  return (
    <Carousel dots={false} dotPosition="left">
      {/* autoplay */}
      {groupList.map((v, index) => {
        return (
          <DataDiv
            data={v}
            key={index}
            pieEndTotalDirvers={pieEndTotalDirvers}
          ></DataDiv>
        )
      })}
    </Carousel>
  )
}
export function DataDiv({ data, pieEndTotalDirvers }: UlDivProps) {
  return (
    <div className="flexr alc juc" style={{ height: 151 }}>
      <div
        style={{ display: 'flex', flexWrap: 'wrap', gap: '9px 104px' }}
        className="alc jub"
      >
        {data?.map((item, index) => {
          return (
            <div className="item-info" key={index}>
              <div className="item-txt">
                <div className="flexr alc">
                  <div className="itme-name">{item.name}</div>
                  <div
                    className="itme-piont flexr"
                    style={{ color: colorLinearData[index][2] }}
                  >
                    {item.piont || 0}
                    <span className="bfh" style={{ marginTop: '1px' }}>
                      %
                    </span>
                  </div>
                </div>
                <div className="item-value">
                  {priceSwitch(
                    item.name === '司机' ? pieEndTotalDirvers : item.value
                  )}
                </div>
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )
}
